package org.openclinic.service.impl;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import org.openclinic.domain.Customer;
import org.openclinic.exception.DomainException;
import org.openclinic.exception.ErrorCodes;
import org.openclinic.repository.CustomerRepository;
import org.openclinic.service.CustomerService;
import org.openclinic.to.CustomerSearchResult;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.dao.DataIntegrityViolationException;
import org.springframework.stereotype.Service;

@Service
public class CustomerServiceImpl implements CustomerService {
	
	@Autowired
	private CustomerRepository customerRepository;
	
	@Override
	public void delete(long id) {
		try {
			customerRepository.delete(id);
		} catch (DataIntegrityViolationException e) {
			throw new DomainException("customer", "name", ErrorCodes.FOREIGN_KEY_VIOLATED, String.valueOf(id));
		}
	}
	
	@Override
	public Customer find(long id) {
		return customerRepository.findOne(id);
	}
	
	@Override
	public List<Customer> list() {
		return customerRepository.findAllCustomers();
	}
	
	@Override
	public Customer save(Customer customer) {
		Date currentDate = new Date();
		
		if (customer.getUserId() == null) {
			customer.setCreationDate(currentDate);
		}
		
		customer.setLastUpdate(currentDate);
		return customerRepository.save(customer);
	}
	
	@Override
	public List<CustomerSearchResult> search(String term) {
		List<Customer> customers = customerRepository.searchCustomers("%" + term.toUpperCase() + "%");
		if (!customers.isEmpty()) {
			SimpleDateFormat sdf = new SimpleDateFormat("dd/MM/yyyy");
			List<CustomerSearchResult> searchResults = new ArrayList<CustomerSearchResult>();
			for (Customer customer : customers) {
				searchResults.add(new CustomerSearchResult(customer.getUserId(), customer.getName(), sdf.format(customer.getBirthdate())));
			}
			return searchResults;
		}
		
		return null;
	}
}
